package rge.orumus.encdb;

import java.io.UnsupportedEncodingException;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import rge.orumus.androidutils.AndroidUtils;
import rge.orumus.encdb.EncDB.RecordType;

public class RecordHeader {
	
	int                    index;
	@Element
	EncDB.RecordType       type;
	@Element
	String                 title;
	
	public RecordHeader(int index, RecordType type, String title) {
		super();
		this.index = index;
		this.type = type;
		this.title = title;
	}

	public RecordHeader(int indexInFile, byte[] content){
		index = indexInFile;
		byte[] decrypted_data = EncDB.Decrypt(content);
		String xmlString = null;
		try {
			xmlString = new String(decrypted_data, "UTF-8");
			
			Serializer serializer = new Persister();
			RecordHeader rh = null;
			
			try {
				rh = serializer.read(RecordHeader.class, xmlString);
			} catch (Exception e) {
				rh = null;
			}
			
			if(null != rh){
				type = rh.type;
				title = rh.title;
			}
			
		} catch (UnsupportedEncodingException e) {
			type = EncDB.RecordType.RECORD_NOT_DECRYPTED;
			title = "Not decrypted";
		}
	}
	
	@Override
	public String toString() {
		return "RecordHeader [index=" + index + ", type=" + type + ", title="
				+ title + "]";
	}

	public String ToHmiString() {
		return String.format("#%2d %s %s", index, type, title);
	}

	public String ToEncodedString(){
		String xmlString = AndroidUtils.ObjectToXmlString(this);
		byte[] inBytes = xmlString.getBytes(AndroidUtils.UTF8CHARSET); 
		byte[] encrypted_data = EncDB.Encrypt(inBytes);
		return AndroidUtils.BytesToBase64Str(encrypted_data);
	}
}
